package com.huatai.saas.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huatai.common.config.MinioAPI;
import com.huatai.common.constant.MinioCommonBucket;
import com.huatai.common.error.exception.ServiceException;
import com.huatai.common.util.AuthUtil;
import com.huatai.common.util.ObjectUtil;
import com.huatai.common.util.PaginationUtils;
import com.huatai.common.util.StringUtil;
import com.huatai.model.dubbo.ModelDubboApi;
import com.huatai.model.entity.FileInfo;
import com.huatai.saas.constant.MinioBucket;
import com.huatai.saas.dto.*;
import com.huatai.saas.entity.*;
import com.huatai.saas.enums.AuthorizationStatusEnum;
import com.huatai.saas.enums.SceneFileStatus;
import com.huatai.saas.enums.UserSceneStatus;
import com.huatai.saas.mapper.SceneFileMapper;
import com.huatai.saas.service.*;
import com.huatai.saas.vo.*;
//import com.sun.org.apache.xpath.internal.operations.Bool;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;

/**
* @author hecai
* @description 针对表【scene_file(场景列表)】的数据库操作Service实现
* @createDate 2024-04-28 10:02:00
*/
@Service
@Slf4j
public class SceneFileServiceImpl extends ServiceImpl<SceneFileMapper, SceneFileEntity> implements SceneFileService {

	@Autowired
	private SceneFileHistoryService sceneFileHistoryService;
	@Autowired
	private SceneFileCollectService sceneFileCollectService;
	@Autowired
	private UserSceneAuthService userSceneAuthService;
	@Autowired
	private MinioAPI minioAPI;
	@Autowired
	private FileService fileService;
	@Autowired
	private ScenePictureService scenePictureService;

	private final static int FILE_DOWNLOAD_ZISE = 1024 * 1024 * 10;

	@DubboReference(check = false)
	private ModelDubboApi modelDubboApi;



	/**
	 * 新增或更新场景
	 * @param sceneFileEntity
	 */
	@Transactional(rollbackFor = Exception.class)
	public void saveOrUpdateSceneFile(SceneFileEntity sceneFileEntity) {
		if(ObjectUtil.isNotEmpty(sceneFileEntity.getPath())){
			throw new ServiceException("请先上传场景文件！！！");
		}
		//若是更新  判断是否是更新底板  若更新了底板  同步更新版本号、历史版本
		if(ObjectUtil.isNotEmpty(sceneFileEntity.getId())){
			SceneFileEntity entity = this.getById(sceneFileEntity.getId());
			sceneFileEntity.setVersion(entity.getVersion());
			sceneFileEntity.setTotalSize(entity.getTotalSize());
			sceneFileEntity.setPath(entity.getPath());
			sceneFileEntity.setIdentifier(entity.getIdentifier());
			super.saveOrUpdate(sceneFileEntity);
			//TODO 更新场景 同时也要新增历史版本  未更新场景 历史版本不变
			if(!entity.getPath().equals(sceneFileEntity.getPath())){
				SceneFileHistoryEntity historyEntity = new SceneFileHistoryEntity();
				historyEntity.setSfId(sceneFileEntity.getId());
				historyEntity.setPath(sceneFileEntity.getPath());
				historyEntity.setTotalSize(sceneFileEntity.getTotalSize());
				historyEntity.setVersion(sceneFileEntity.getVersion());
				sceneFileHistoryService.save(historyEntity);
			}
		}
		else{
			sceneFileEntity.setId(IdWorker.getId());
			SceneFileHistoryEntity historyEntity = new SceneFileHistoryEntity();
			historyEntity.setSfId(sceneFileEntity.getId());
			historyEntity.setPath(sceneFileEntity.getPath());
			historyEntity.setTotalSize(sceneFileEntity.getTotalSize());
			historyEntity.setVersion(sceneFileEntity.getVersion());
			super.save(sceneFileEntity);
			sceneFileHistoryService.save(historyEntity);
		}
	}

	/**
	 * 新增
	 * @param sceneFileEntity
	 * @return
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public Long saveSceneFile(SceneFileDto sceneFileEntity) {
		sceneFileEntity.setId(IdWorker.getId());
//		if (StringUtil.isEmpty(sceneFileEntity.getOpenId())){
//			throw new ServiceException("场景唯一标识不能为空");
//		}
//		SceneFileEntity one = this.getOne(Wrappers.<SceneFileEntity>lambdaQuery().eq(SceneFileEntity::getOpenId, sceneFileEntity.getOpenId()));
//		if(ObjectUtil.isNotEmpty(one)){
//			throw new ServiceException("场景唯一标识已经存在，请联系场景侧确定");
//		}
		List<PictureIsMainDto> picturePath = sceneFileEntity.getPictureList();
		if(ObjectUtil.isEmpty(picturePath)){
			throw new ServiceException("场景轮播图不能为空");
		}

		//TODO  处理轮播图的逻辑
		List<ScenePictureEntity> savePictureList=new ArrayList<>();
		int j=0;
		for (int i = 0; i < picturePath.size(); i++) {
			PictureIsMainDto pictureIsMainDto = picturePath.get(i);
			//处理轮播图逻辑  只能有一个主图
			if(pictureIsMainDto.getIsMain()==1){
				j++;
			}
			if(j>1){
				throw new ServiceException("轮播图只能有一个主图");
			}
			ScenePictureEntity scenePictureEntity = new ScenePictureEntity();
			scenePictureEntity.setId(IdWorker.getId());
			scenePictureEntity.setSfId(sceneFileEntity.getId());
			scenePictureEntity.setPath(pictureIsMainDto.getPicturePath());
			scenePictureEntity.setIsMain(pictureIsMainDto.getIsMain());
			//视频限定只能传mp4格式
			String[] split = pictureIsMainDto.getPicturePath().split("\\.");
			scenePictureEntity.setContentType("image");
			if(split[split.length-1].toLowerCase().equals("mp4")){
				scenePictureEntity.setContentType("mp4");
			}
			savePictureList.add(scenePictureEntity);
		}
		if(j==0){
			throw new ServiceException("轮播图至少需要有一个主图");
		}
		//TODO 保存轮播图
		scenePictureService.saveBatch(savePictureList);
		sceneFileEntity.setStatus(SceneFileStatus.EXCEPTION.getCode());
		sceneFileEntity.setVersion("v1");
		SceneFileEntity entity = BeanUtil.copyProperties(sceneFileEntity, SceneFileEntity.class);
		this.save(entity);
		return sceneFileEntity.getId();
	}

	/**
	 * 更新场景同步更新历史版本信息
	 * @param sceneFileEntity
	 * @return
	 */
	@Override
	public Boolean updateSceneFilePath(SceneFileEntity sceneFileEntity) {
		Long id = sceneFileEntity.getId();
		if(ObjectUtil.isEmpty(id)){
			throw new ServiceException("ID不能为空");
		}
		if(StringUtil.isEmpty(sceneFileEntity.getPath())){
			throw new ServiceException("存储的文件不能为空！！");
		}
		SceneFileEntity entity = this.getById(id);
		if(ObjectUtil.isEmpty(entity)){
			throw new ServiceException("场景不存在");
		}
//		//TODO  此处还差远程调用dubbo查询文件详细信息  totalSize identifier
//		FileInfo fileInfo = modelDubboApi.getFileInfo(sceneFileEntity.getPath());
//		if(fileInfo == null){
//			throw new ServiceException("文件上传失败！！！");
//		}
		entity.setPath(sceneFileEntity.getPath());

		//处理秒传情况
		try{
			entity.setTotalSize(fileService.getFileSize(sceneFileEntity.getPath()));
		}catch (Exception e){
			log.error("场景更新文件路径未获取到场景大小"+e.getMessage());
		}
//		entity.setTotalSize(fileService.getFileSize(sceneFileEntity.getPath()));
		//已完成状态 则是更新底板
		if(entity.getStatus() == SceneFileStatus.NORMAL.getCode()){
			//同步更新版本号码
			entity.setVersion(getVersion(entity.getVersion()));
		}else {  //未完成 保存底板信息
			entity.setStatus(SceneFileStatus.NORMAL.getCode());
		}
		//保存进历史版本
		SceneFileHistoryEntity historyEntity = new SceneFileHistoryEntity();
		historyEntity.setSfId(entity.getId());
		historyEntity.setPath(entity.getPath());
		historyEntity.setTotalSize(entity.getTotalSize());
		historyEntity.setVersion(entity.getVersion());
		historyEntity.setDescription(entity.getDescription());
		sceneFileHistoryService.save(historyEntity);
		return this.updateById(entity);
	}

	/**
	 * 更新场景基本信息
	 * @param sceneFileEntity
	 * @return
	 */
	@Transactional(rollbackFor = Exception.class)
	public Boolean updateSceneFile(SceneFileDto sceneFileEntity) {
		Long id = sceneFileEntity.getId();
		if(ObjectUtil.isEmpty(id)){
			throw new ServiceException("ID不能为空");
		}
		SceneFileEntity entity = this.getById(id);
		entity.setFileName(sceneFileEntity.getFileName());
		entity.setDescription(sceneFileEntity.getDescription());
		entity.setPrice(sceneFileEntity.getPrice());
		entity.setIndustryKey(sceneFileEntity.getIndustryKey());
		//TODO  处理轮播图的逻辑
		List<PictureIsMainDto> picturePath = sceneFileEntity.getPictureList();
		List<ScenePictureEntity> savePictureList=new ArrayList<>();
		int j=0;
		for (int i = 0; i < picturePath.size(); i++) {
			PictureIsMainDto pictureIsMainDto = picturePath.get(i);
			//处理轮播图逻辑  只能有一个主图
			if(pictureIsMainDto.getIsMain()==1){
				j++;
			}
			if(j>1){
				throw new ServiceException("轮播图只能有一个主图");
			}
			ScenePictureEntity scenePictureEntity = new ScenePictureEntity();
			scenePictureEntity.setSfId(sceneFileEntity.getId());
			//TODO  此处新加上没有调整图片的逻辑  返回为http://192.168.1.1:8080/bukut/xxxx.jpg
			String pathUrl = minioAPI.getCOMINFO()+"/"+MinioCommonBucket.HUATAI_PUB_BUCKET_URL+"/";
			String path = pictureIsMainDto.getPicturePath().replace(pathUrl,"");
			scenePictureEntity.setPath(path);
			scenePictureEntity.setIsMain(pictureIsMainDto.getIsMain());
			//视频限定只能传mp4格式
			String[] split = pictureIsMainDto.getPicturePath().split("\\.");
			scenePictureEntity.setContentType("image");
			if(split[split.length-1].equals("mp4")){
				scenePictureEntity.setContentType("mp4");
			}
			savePictureList.add(scenePictureEntity);
		}
		if(j==0){
			throw new ServiceException("轮播图至少需要有一个主图");
		}

		List<ScenePictureEntity> list = scenePictureService.list(Wrappers.<ScenePictureEntity>lambdaQuery().eq(ScenePictureEntity::getSfId, entity.getId()));
		//判断两个文件是否一模一样  不更新图片
		if(savePictureList.equals(list)){
			savePictureList.clear();
		}
		if(ObjectUtil.isNotEmpty(savePictureList) && savePictureList.size()>0){
			//删除原有的图片
			scenePictureService.remove(Wrappers.<ScenePictureEntity>lambdaQuery().eq(ScenePictureEntity::getSfId,entity.getId()));
			//TODO 保存轮播图
			scenePictureService.saveBatch(savePictureList);
		}
		return this.updateById(entity);
	}

	/**
	 * 获取场景问题
	 * @param version
	 * @return
	 */
	private String getVersion(String version){
		version = version.replace("v","");
		int versionInt = Integer.parseInt(version)+1;
//		String issue = version.substring(0, 8);
//		String yyyyMMdd = DateUtil.format(DateUtil.date(), "yyyyMMdd");
//		//相等则是同一天更新多个版本
//		if(issue.equals(yyyyMMdd)){
//			Integer num = Integer.parseInt(version.substring(8, 10))+1;
//			if(num < 10){
//				version = issue + "0" + num;
//			}else {
//				version = issue + num;
//			}
//		}else {//非同一天处理版本号
//			version = yyyyMMdd + "01";
//		}
		return "v"+versionInt;
	}

	/**
	 * 分页获取场景列表数据
	 * @param dto
	 * @return
	 */
	public IPage<SceneFileEntity> getFilePageList(BackFileListQueryDto dto){
		IPage<SceneFileEntity> page = PaginationUtils.getPage(dto.getPage(),dto.getSize());
		LambdaQueryWrapper<SceneFileEntity> qw = new LambdaQueryWrapper<SceneFileEntity>();
		qw.like(StringUtil.isNotBlank(dto.getFileName()), SceneFileEntity::getFileName, dto.getFileName());
		qw.like(StringUtil.isNotBlank(dto.getIndustryKey()), SceneFileEntity::getIndustryKey, dto.getIndustryKey());
		qw.orderByDesc(SceneFileEntity::getCreateTime);
		IPage<SceneFileEntity> pageDataList = super.baseMapper.selectPage(page, qw);
		List<SceneFileEntity> records = pageDataList.getRecords();
		if(ObjectUtil.isNotEmpty(records)){
			List<Long> sfIds = records.stream().map(p -> p.getId()).collect(Collectors.toList());
			List<ScenePictureEntity> list = scenePictureService.list(Wrappers.<ScenePictureEntity>lambdaQuery().in(ScenePictureEntity::getSfId, sfIds));
			if(ObjectUtil.isNotEmpty(list)){
				records.stream().forEach(entity -> {
                    String signedUrl = null;
                    try {
                        signedUrl = minioAPI.getSignedUrl(MinioBucket.MODEL_BUCKET_NAME_PRIVATE, entity.getPath(), 86400);
                    } catch (Exception e) {
                        log.error(e.getMessage());
                    }
                    entity.setPath(signedUrl);
					entity.setIsScene(false);
					if(StringUtil.isNotBlank(entity.getPath())){
						entity.setIsScene(true);
					}
					ScenePictureEntity scenePictureEntity = list.stream().filter(p -> p.getSfId().equals(entity.getId()) && p.getIsMain().equals(1)).findFirst().orElse(null);
					if(ObjectUtil.isNotEmpty(scenePictureEntity)){
						entity.setPictureUrl(minioAPI.getCOMINFO()+"/"+MinioCommonBucket.HUATAI_PUB_BUCKET_URL+"/"+scenePictureEntity.getPath());
					}
				});
			}
		}
		return pageDataList;
	}


	/**
	 * 收藏场景
	 */
	public Boolean collectSceneFile(Long id) {
		SceneFileEntity entity = super.getById(id);
		if(ObjectUtil.isEmpty(entity)){
			throw new ServiceException("该场景不存在！！！");
		}
		SceneFileCollectEntity collectEntity = new SceneFileCollectEntity();
		collectEntity.setSfId(id);
		collectEntity.setUserId(AuthUtil.getUser().getUserId());
		return sceneFileCollectService.save(collectEntity);
	}

	/**
	 * 取消场景收藏
	 * @param id
	 * @return
	 */
	@Override
	public Boolean cancelCollectSceneFile(Long id) {
		SceneFileCollectEntity entity = new SceneFileCollectEntity();
		entity.setSfId(id);
		entity.setUserId(AuthUtil.getUser().getUserId());
		return sceneFileCollectService.remove(new LambdaQueryWrapper<SceneFileCollectEntity>().eq(SceneFileCollectEntity::getSfId, id).eq(SceneFileCollectEntity::getUserId, AuthUtil.getUser().getUserId()));
	}

	/**
	 * 删除场景 逻辑删除
	 * @param ids
	 */
	public void delFileListByIds(List<Long> ids) {
		super.removeByIds(ids);
	}

	/**
	 * 根据场景id 获取场景历史版本
	 */
	public List<SceneFileHistoryInfoVo> getSceneFileHistoryList(Long id) {
		List<SceneFileHistoryInfoVo> sceneFileHistoryVo = super.baseMapper.getSceneFileHistory(id);
		return sceneFileHistoryVo;
	}


	/**
	 * 用户自己获取自己的场景列表
	 */
	public IPage<SceneFileAuthUserVo> getPageSceneListByUserId(BackFileListQueryDto dto){
		Long userId = AuthUtil.getUser().getUserId();
		IPage<SceneFileAuthUserVo> pageData = super.baseMapper.getSceneFilePageList(PaginationUtils.getPage(dto.getPage(),dto.getSize()),userId, dto.getIndustryKey(),
			DateUtil.format(LocalDateTime.now()," yyyy-MM-dd HH:mm:ss"), dto.getFileName());
		List<SceneFileAuthUserVo> records = pageData.getRecords();
		if(records!=null && records.size()>0){
			List<Long> collect = records.stream().map(p -> p.getId()).collect(Collectors.toList());
			List<ScenePictureEntity> scenePictureEntityList = scenePictureService.list(Wrappers.<ScenePictureEntity>lambdaQuery().in(ScenePictureEntity::getSfId, collect));
			records.stream().forEach(data->{
				ScenePictureEntity scenePictureEntity = scenePictureEntityList.stream().filter(p -> p.getIsMain().equals(1) && p.getSfId().equals(data.getId())).findFirst().orElse(null);
				if(ObjectUtil.isNotEmpty(scenePictureEntity)){
					data.setPictureUrl(minioAPI.getCOMINFO()+"/"+MinioCommonBucket.HUATAI_PUB_BUCKET_URL+"/"+scenePictureEntity.getPath());
					data.setPicturePath(scenePictureEntity.getPath());
				}
			});
		}
		return pageData;
//		Page<UserSceneAuthEntity> pageData = userSceneAuthService.page(PaginationUtils.getPage(dto.getPage(), dto.getSize()), Wrappers.<UserSceneAuthEntity>lambdaQuery()
//			.eq(UserSceneAuthEntity::getUserId, userId)
//			.ge(UserSceneAuthEntity::getAuthEndTime, LocalDateTime.now()));
//		List<SceneFileAuthUserVo> records = pageData.getRecords();
//		List<SceneFileAuthUserVo> dataList = new ArrayList<>();
//		if(records!=null && records.size()>0){
//			List<Long> collect = records.stream().map(p -> p.getSfId()).collect(Collectors.toList());
//			List<SceneFileEntity> list = this.list(Wrappers.<SceneFileEntity>lambdaQuery().in(ObjectUtil.isNotEmpty(collect),SceneFileEntity::getId, collect));
//			List<ScenePictureEntity> scenePictureEntityList = scenePictureService.list(Wrappers.<ScenePictureEntity>lambdaQuery().in(ScenePictureEntity::getSfId, collect));
//			records.stream().forEach(data->{
//				SceneFileAuthUserVo sceneFileAuthInfoVo = BeanUtil.copyProperties(data, SceneFileAuthUserVo.class);
//				ScenePictureEntity scenePictureEntity = scenePictureEntityList.stream().filter(p -> p.getIsMain().equals(1) && p.getSfId().equals(data.getSfId())).findFirst().orElse(null);
//				if(ObjectUtil.isNotEmpty(scenePictureEntity)){
//					sceneFileAuthInfoVo.setPictureUrl(minioAPI.getCOMINFO()+"/"+MinioCommonBucket.HUATAI_PUB_BUCKET_URL+"/"+scenePictureEntity.getPath());
//				}
//				//判断是否过期
//				if(judgmentEqualTime(LocalDateTime.now(),data.getAuthEndTime())){
//					sceneFileAuthInfoVo.setStatus("正常");
//				}else {
//					sceneFileAuthInfoVo.setStatus("授权已过期");
//				}
//				SceneFileEntity entity = list.stream().filter(p -> p.getId().equals(data.getSfId())).findFirst().orElse(null);
//				sceneFileAuthInfoVo.setId(entity.getId());
//				sceneFileAuthInfoVo.setUsaId(data.getId());
//				sceneFileAuthInfoVo.setFileName(entity.getFileName());
//				sceneFileAuthInfoVo.setTotalSize(entity.getTotalSize());
//				sceneFileAuthInfoVo.setDescription(entity.getDescription());
//				dataList.add(sceneFileAuthInfoVo);
//			});
//		}
//		sceneFilePageList.setPages(pageData.getPages());
//		sceneFilePageList.setRecords(dataList);
//		sceneFilePageList.setTotal(pageData.getTotal());
//		sceneFilePageList.setCurrent(pageData.getCurrent());
//		sceneFilePageList.setSize(pageData.getSize());
//		return sceneFilePageList;
	}

	/**
	 * 用户端获取场景列表
	 * @param dto
	 * @return
	 */
	@Override
	public IPage<SceneFileAuthInfoVo> getCollectPageData(AuthSceneListQueryDto dto){
		IPage<SceneFileEntity> page = PaginationUtils.getPage(dto.getPage(),dto.getSize());
		IPage<SceneFileEntity> pageData = super.page(page,Wrappers.<SceneFileEntity>lambdaQuery()
			.like(StringUtil.isNotBlank(dto.getFileName()),SceneFileEntity::getFileName, dto.getFileName())
			.eq(StringUtil.isNotBlank(dto.getIndustryKey()),SceneFileEntity::getIndustryKey, dto.getIndustryKey())
			.orderByDesc(SceneFileEntity::getCreateTime));
		List<Long> ids = pageData.getRecords().stream().map(p -> p.getId()).collect(Collectors.toList());
		List<SceneFileCollectEntity> collectEntityList = sceneFileCollectService.list(Wrappers.<SceneFileCollectEntity>lambdaQuery()
			.eq(SceneFileCollectEntity::getUserId, AuthUtil.getUser().getUserId())
			.in(ObjectUtil.isNotEmpty(ids),SceneFileCollectEntity::getSfId, ids));
		List<ScenePictureEntity> pictureEntityList = scenePictureService.list(Wrappers.<ScenePictureEntity>lambdaQuery().in(ScenePictureEntity::getSfId, ids));
		List<SceneFileAuthInfoVo> dataList = new ArrayList<>();
		pageData.getRecords().stream().forEach(data->{
			SceneFileAuthInfoVo sceneFileAuthInfoVo = BeanUtil.copyProperties(data, SceneFileAuthInfoVo.class);
			sceneFileAuthInfoVo.setSelectStatus(false);
			sceneFileAuthInfoVo.setIndustryKey(data.getIndustryKey());
			ScenePictureEntity scenePictureEntity = pictureEntityList.stream().filter(p -> p.getSfId().equals(data.getId()) && p.getIsMain().equals(1)).findFirst().orElse(null);
			if(ObjectUtil.isNotEmpty(scenePictureEntity)){
				sceneFileAuthInfoVo.setPictureUrl(minioAPI.getCOMINFO()+"/"+MinioCommonBucket.HUATAI_PUB_BUCKET_URL+"/"+scenePictureEntity.getPath());
			}
			if(collectEntityList.stream().anyMatch(p->p.getSfId().equals(data.getId()))){
				sceneFileAuthInfoVo.setSelectStatus(true);
			}
			dataList.add(sceneFileAuthInfoVo);
		});
		IPage<SceneFileAuthInfoVo> collectPageData = new Page<>();
		collectPageData.setRecords(dataList);
		collectPageData.setTotal(pageData.getTotal());
		collectPageData.setSize(pageData.getSize());
		collectPageData.setCurrent(pageData.getCurrent());
		collectPageData.setPages(pageData.getPages());
		return collectPageData;
	}

	/**
	 * 用户收藏场景列表
	 * @param dto
	 * @return
	 */
	public IPage<SceneFileCollectUserVo> getPageSceneCollectListByUserId(BackFileListQueryDto dto){
		IPage<SceneFileCollectUserVo> page = PaginationUtils.getPage(dto.getPage(),dto.getSize());
		IPage<SceneFileCollectUserVo> sceneFileCollectPageList = super.baseMapper.getSceneFileCollectPageList(page, AuthUtil.getUser().getUserId(),dto.getIndustryKey(),dto.getFileName());
		List<SceneFileCollectUserVo> records = sceneFileCollectPageList.getRecords();
		if(ObjectUtil.isNotEmpty(records)){
			List<Long> sfIds = records.stream().map(p -> p.getId()).collect(Collectors.toList());
			List<ScenePictureEntity> list = scenePictureService.list(Wrappers.<ScenePictureEntity>lambdaQuery().in(ScenePictureEntity::getSfId, sfIds));
			records.stream().forEach(data->{
				ScenePictureEntity scenePictureEntity = list.stream().filter(p -> p.getIsMain().equals(1) && sfIds.contains(p.getSfId())).findFirst().orElse(null);
				if(ObjectUtil.isNotEmpty(scenePictureEntity)){
					data.setPictureUrl(minioAPI.getCOMINFO()+"/"+MinioCommonBucket.HUATAI_PUB_BUCKET_URL+"/"+scenePictureEntity.getPath());
				}
				data.setPath("");
			});
		}
		return sceneFileCollectPageList;
	}

	/**
	 * 根据用户id  获取场景列表，并判断场景是否被授权
	 * @param dto
	 * @return
	 */
	@Override
	public IPage<SceneFileAuthInfoVo> getIsAuthPageData(AuthSceneListQueryDto dto){
		if(ObjectUtil.isEmpty(dto.getUserId())){
			throw new ServiceException("用户ID不能为空");
		}
		IPage<SceneFileAuthInfoVo> page = PaginationUtils.getPage(dto.getPage(),dto.getSize());
		String authEndTime = DateUtil.format(LocalDateTime.now()," yyyy-MM-dd HH:mm:ss");
		IPage<SceneFileAuthInfoVo> vo = this.baseMapper.getIsAuthPageData(page, dto.getUserId(), dto.getFileName(),dto.getIndustryKey(),dto.getSelectStatus(),authEndTime);
		List<SceneFileAuthInfoVo> records = vo.getRecords();
		if(ObjectUtil.isNotEmpty(records)){
			List<Long> sfIds = records.stream().map(p -> p.getId()).collect(Collectors.toList());
			List<ScenePictureEntity> list = scenePictureService.list(Wrappers.<ScenePictureEntity>lambdaQuery().in(ScenePictureEntity::getSfId, sfIds));
			records.stream().forEach(data -> {
				ScenePictureEntity scenePictureEntity = list.stream().filter(p -> p.getSfId().equals(data.getId()) && p.getIsMain().equals(1)).findFirst().orElse(null);
				if(ObjectUtil.isNotEmpty(scenePictureEntity)){
					data.setPictureUrl(minioAPI.getCOMINFO() + "/" + MinioCommonBucket.HUATAI_PUB_BUCKET_URL + "/" + scenePictureEntity.getPath());
				}
			});
		}
		return vo;
//		IPage<SceneFileEntity> pageData = this.page(page,Wrappers.<SceneFileEntity>lambdaQuery().orderByDesc(SceneFileEntity::getCreateTime));
//		List<Long> ids = pageData.getRecords().stream().map(p -> p.getId()).collect(Collectors.toList());
//		List<UserSceneAuthEntity> collectEntityList = userSceneAuthService.list(Wrappers.<UserSceneAuthEntity>lambdaQuery()
//			.eq(ObjectUtil.isNotEmpty(dto.getUserId()),UserSceneAuthEntity::getUserId, dto.getUserId())
//			.in(ObjectUtil.isNotEmpty(ids),UserSceneAuthEntity::getSfId, ids));
//		List<SceneFileAuthInfoVo> dataList = new ArrayList<>();
//		pageData.getRecords().stream().forEach(data->{
//			SceneFileAuthInfoVo sceneFileAuthInfoVo = BeanUtil.copyProperties(data, SceneFileAuthInfoVo.class);
//			sceneFileAuthInfoVo.setSelectStatus(false);
//			if(StringUtil.isNotBlank(data.getPicturePath())){
//				sceneFileAuthInfoVo.setPictureUrl(minioAPI.getCOMINFO()+"/"+MinioCommonBucket.HUATAI_PUB_BUCKET_URL+"/"+data.getPicturePath());
//			}
//			if(collectEntityList.stream().anyMatch(p->p.getSfId().equals(data.getId()))){
//				sceneFileAuthInfoVo.setSelectStatus(true);
//			}
//			dataList.add(sceneFileAuthInfoVo);
//		});
//		IPage<SceneFileAuthInfoVo> collectPageData = new Page<>();
//		collectPageData.setRecords(dataList);
//		collectPageData.setTotal(pageData.getTotal());
//		collectPageData.setSize(pageData.getSize());
//		collectPageData.setCurrent(pageData.getCurrent());
//		collectPageData.setPages(pageData.getPages());
//		return collectPageData;
	}

	/**
	 * 根据用户id获取用户已授权列表
	 * @param dto
	 * @return
	 */
	@Override
	public IPage<SceneFileAuthInfoVo> getByUserIdPageData(AuthSceneListQueryDto dto){
		if(ObjectUtil.isEmpty(dto.getUserId())){
			throw new ServiceException("用户ID不能为空");
		}
		IPage<SceneFileAuthInfoVo> page = PaginationUtils.getPage(dto.getPage(),dto.getSize());
		String authEndTime = DateUtil.format(LocalDateTime.now()," yyyy-MM-dd HH:mm:ss");
		IPage<SceneFileAuthInfoVo> vo = this.baseMapper.getIsAuthPageDataInfo(page,dto.getUserId(),dto.getIndustryKey(),dto.getFileName(),authEndTime);
		List<SceneFileAuthInfoVo> records = vo.getRecords();
		if(ObjectUtil.isNotEmpty(records)){
			List<Long> sfIds = records.stream().map(p -> p.getId()).collect(Collectors.toList());
			List<ScenePictureEntity> list = scenePictureService.list(Wrappers.<ScenePictureEntity>lambdaQuery().in(ScenePictureEntity::getSfId, sfIds));
			if(ObjectUtil.isNotEmpty(list)){
				records.stream().forEach(data->{
					data.setSelectStatus(true);
					ScenePictureEntity scenePictureEntity = list.stream().filter(p -> p.getSfId().equals(data.getId()) && p.getIsMain().equals(1)).findFirst().orElse(null);
					if(ObjectUtil.isNotEmpty(scenePictureEntity)){
						data.setPictureUrl(minioAPI.getCOMINFO()+"/"+MinioCommonBucket.HUATAI_PUB_BUCKET_URL+"/"+scenePictureEntity.getPath());
					}
				});
			}
		}
		return vo;
	}

	/**
	 * 授权用户场景
	 * @param dto
	 * @return
	 */
	public Boolean authSceneUsers(AuthSceneUserDto dto){
		//现获取数据
		List<SceneFileEntity> sceneFileEntities = this.list(Wrappers.<SceneFileEntity>lambdaQuery().in(SceneFileEntity::getId, dto.getSfId()));
		List<UserSceneAuthEntity> list = userSceneAuthService.list(Wrappers.<UserSceneAuthEntity>lambdaQuery()
			.eq(ObjectUtil.isNotEmpty(dto.getUserId()),UserSceneAuthEntity::getUserId,dto.getUserId()));
		List<UserSceneAuthEntity> entityList = new ArrayList<>();
		Long userId = AuthUtil.getUser().getUserId();
		for (int i = 0; i < dto.getSfId().length; i++) {
			Long[] sfIds = dto.getSfId();
			//判断是否存在授权信息  授权信息是否已经过期  过期从新授权  未过期暂时剔除本次授权信息
			Long sfId = sfIds[i];
			SceneFileEntity sceneFileEntity = sceneFileEntities.stream().filter(p -> p.getId().equals(sfId)).findFirst().orElse(null);
			if(list.stream().anyMatch(p->p.getSfId().equals(sfId) && judgmentEqualTime(dto.getAuthEndTime(),p.getAuthEndTime()))){
				continue;
			}
			UserSceneAuthEntity entity = new UserSceneAuthEntity();
			entity.setSfId(sfId);
			entity.setAuthUserId(userId);
			entity.setUserId(dto.getUserId());
			entity.setOpenId(sceneFileEntity.getOpenId());
			entity.setAuthStartTime(dto.getAuthStartTime());
			entity.setAuthEndTime(dto.getAuthEndTime());
			entity.setStatus(UserSceneStatus.NORMAL.getCode());
			entity.setRemark(dto.getRemark());
			String signature =IdUtil.fastSimpleUUID()+IdUtil.fastSimpleUUID();
			entity.setSignature(signature.toUpperCase(Locale.ROOT));
			entityList.add(entity);
		}
		return userSceneAuthService.saveBatch(entityList);
	}

	/**
	 * 判断时间时间是否小于等于
	 * @param startTime
	 * @param endTime
	 * @return
	 */
	private Boolean judgmentEqualTime(LocalDateTime startTime,LocalDateTime endTime){
		if(startTime.isBefore(endTime) ||startTime.equals(endTime)){
			return true;
		}
		return false;
	}

	/**
	 * 客户端获取授权签名
	 * @param id
	 * @return
	 */
	@Override
	public String getSignature(Long id){
		UserSceneAuthEntity entity = userSceneAuthService.getById(id);
		if (ObjectUtil.isEmpty(entity)){
			throw new ServiceException("未授权");
		}
		return entity.getSignature();
	}


	/**
	 * UE侧查询当前场景是否授权
	 * @param signature 签名
	 * @param openId    场景内部唯一标识
	 * @return
	 */
	@Override
	public AuthorizationVO getSceneFileAuthInfo(String signature,String openId){
		AuthorizationVO vo = new AuthorizationVO();
		UserSceneAuthEntity entity = userSceneAuthService.getOne(Wrappers.<UserSceneAuthEntity>lambdaQuery()
			.eq(StringUtil.isNotBlank(signature),UserSceneAuthEntity::getSignature, signature));
//			.eq(StringUtil.isNotBlank(openId),UserSceneAuthEntity::getOpenId, openId));
		if(ObjectUtil.isEmpty(entity)){
			vo.setCode(AuthorizationStatusEnum.EXPIRED.getCode());
			vo.setMessage(AuthorizationStatusEnum.EXPIRED.getMessage());
			vo.setIsSuccess(AuthorizationStatusEnum.EXPIRED.getSuccess());
		}else if(LocalDateTime.now().isAfter(entity.getAuthEndTime())){
			vo.setMessage(AuthorizationStatusEnum.FAIL.getMessage());
			vo.setCode(AuthorizationStatusEnum.FAIL.getCode());
			vo.setIsSuccess(AuthorizationStatusEnum.FAIL.getSuccess());
		}else {
			vo.setMessage(AuthorizationStatusEnum.SUCCESS.getMessage());
			vo.setCode(AuthorizationStatusEnum.SUCCESS.getCode());
			vo.setIsSuccess(AuthorizationStatusEnum.SUCCESS.getSuccess());
		}
		return vo;
	}

	/**
	 * 取消授权
	 * @param scId
	 * @param userId
	 * @return
	 */
	@Override
	public Boolean disableSceneUser(Long[] scIds,Long userId){
		return userSceneAuthService.remove(Wrappers.<UserSceneAuthEntity>lambdaQuery()
			.in(ObjectUtil.isNotEmpty(scIds),UserSceneAuthEntity::getSfId,scIds)
			.eq(ObjectUtil.isNotEmpty(userId),UserSceneAuthEntity::getUserId,userId));
	}

	/**
	 * 单个文件下载
	 * @param usaId
	 */
	@Override
	public void  download(Long usaId){
		UserSceneAuthEntity entity = userSceneAuthService.getById(usaId);
		if(ObjectUtil.isEmpty(entity)){
			throw new ServiceException("授权场景不存在");
		}
		if(entity.getAuthEndTime().isBefore(LocalDateTime.now())){
			throw new ServiceException("授权已过期");
		}
		SceneFileEntity sceneFileEntity = super.getById(entity.getSfId());
		if(ObjectUtil.isEmpty(sceneFileEntity)){
			throw new ServiceException("场景不存在");
		}
		if(StringUtil.isEmpty(sceneFileEntity.getPath())){
			throw new ServiceException("未上传场景文件");
		}
		fileService.download(sceneFileEntity.getPath());
	}

	/**
	 * 单个文件下载
	 * @param usaId
	 */
	@Override
	public void  downloadMessanger(Long id){
		SceneFileEntity sceneFileEntity = this.getById(id);
		if(ObjectUtil.isEmpty(sceneFileEntity) ){
			throw new ServiceException("场景不存在");
		}
		if(StringUtil.isEmpty(sceneFileEntity.getPath())){
			throw new ServiceException("未上传场景文件");
		}
		fileService.download(sceneFileEntity.getPath());
	}

	/**
	 * 场景文件历史版本下载
	 * @param id 历史场景id
	 */
	@Override
	public void  downloadHistoryScene(Long id,String version){
		SceneFileHistoryEntity historyEntity = sceneFileHistoryService.getOne(Wrappers.<SceneFileHistoryEntity>lambdaQuery().eq(SceneFileHistoryEntity::getSfId, id)
			.eq(SceneFileHistoryEntity::getVersion, version));
		if(ObjectUtil.isEmpty(historyEntity)){
			throw new ServiceException("历史场景不存在");
		}
		if(StringUtil.isEmpty(historyEntity.getPath())){
			throw new ServiceException("未上传场景文件");
		}
		LambdaQueryWrapper<UserSceneAuthEntity> qw = Wrappers.<UserSceneAuthEntity>lambdaQuery()
			.eq(ObjectUtil.isNotEmpty(historyEntity.getSfId()),UserSceneAuthEntity::getSfId,id)
			.eq(UserSceneAuthEntity::getUserId, AuthUtil.getUser().getUserId())
			.ge(UserSceneAuthEntity::getAuthEndTime, LocalDateTime.now());
		UserSceneAuthEntity entity = userSceneAuthService.getOne(qw);
		if (ObjectUtil.isEmpty(entity)){
			throw new ServiceException("授权已过期或授权不存在");
		}
		fileService.download(historyEntity.getPath());
	}

	/**
	 * 获取分片数量
	 * @param sfId
	 * @return
	 */
	@Override
	public Integer getFilePartHistoryNums(Long id,String version) {
		SceneFileHistoryEntity historyEntity = sceneFileHistoryService.getOne(Wrappers.<SceneFileHistoryEntity>lambdaQuery().eq(SceneFileHistoryEntity::getSfId, id)
			.eq(SceneFileHistoryEntity::getVersion, version));
		if(ObjectUtil.isEmpty(historyEntity)){
			throw new ServiceException("历史场景不存在");
		}
		if(StringUtil.isEmpty(historyEntity.getPath())){
			throw new ServiceException("未上传场景文件");
		}
		LambdaQueryWrapper<UserSceneAuthEntity> qw = Wrappers.<UserSceneAuthEntity>lambdaQuery()
			.eq(ObjectUtil.isNotEmpty(historyEntity.getSfId()),UserSceneAuthEntity::getSfId,id)
			.eq(UserSceneAuthEntity::getUserId, AuthUtil.getUser().getUserId())
			.ge(UserSceneAuthEntity::getAuthEndTime, LocalDateTime.now());
		UserSceneAuthEntity entity = userSceneAuthService.getOne(qw);
		if (ObjectUtil.isEmpty(entity)){
			throw new ServiceException("授权已过期或授权不存在");
		}
		return (int)Math.ceil((fileService.getFileSize(historyEntity.getPath()) / (double)FILE_DOWNLOAD_ZISE));
	}

	/**
	 * 获取场景文件分片下载
	 * @param id 历史场景id
	 */
	@Override
	public void partDowmloadHistoryScene(Long id,String version,int partIndex){
		SceneFileHistoryEntity historyEntity = sceneFileHistoryService.getOne(Wrappers.<SceneFileHistoryEntity>lambdaQuery().eq(SceneFileHistoryEntity::getSfId, id)
			.eq(SceneFileHistoryEntity::getVersion, version));
		if(ObjectUtil.isEmpty(historyEntity)){
			throw new ServiceException("历史场景不存在");
		}
		if(StringUtil.isEmpty(historyEntity.getPath())){
			throw new ServiceException("未上传场景文件");
		}
		LambdaQueryWrapper<UserSceneAuthEntity> qw = Wrappers.<UserSceneAuthEntity>lambdaQuery()
			.eq(ObjectUtil.isNotEmpty(historyEntity.getSfId()),UserSceneAuthEntity::getSfId,id)
			.eq(UserSceneAuthEntity::getUserId, AuthUtil.getUser().getUserId())
			.ge(UserSceneAuthEntity::getAuthEndTime, LocalDateTime.now());
		UserSceneAuthEntity entity = userSceneAuthService.getOne(qw);
		if (ObjectUtil.isEmpty(entity)){
			throw new ServiceException("授权已过期或授权不存在");
		}
		fileService.download(historyEntity.getPath(),partIndex);
	}

	/**
	 * 获取分片数量
	 * @param sfId
	 * @return
	 */
	@Override
	public int getFilePartNums(Long sfId) {
		SceneFileEntity entity = super.getById(sfId);
		if(ObjectUtil.isEmpty(entity)){
			throw new ServiceException("场景不存在");
		}
		return (int)Math.ceil((fileService.getFileSize(entity.getPath()) / (double)FILE_DOWNLOAD_ZISE));
	}

	/**
	 * 获取场景文件分片下载
	 * @param sfId
	 */
	@Override
	public void partDowmloadScene(Long sfId,int partIndex){
		SceneFileEntity entity = super.getById(sfId);
		if(ObjectUtil.isEmpty(entity)){
			throw new ServiceException("场景不存在");
		}
		fileService.download(entity.getPath(),partIndex);
	}

	/**
	 * 获取场景基本信息
	 * @param sfId
	 * @return
	 */
	@Override
	public SceneFileEntityVo getSceneFileInfo(Long sfId) throws Exception {
		SceneFileEntity sceneFile = super.getById(sfId);
		if(sceneFile==null){
			throw new ServiceException("场景不存在");
		}
		SceneFileEntityVo sceneFileEntityVo = BeanUtil.copyProperties(sceneFile, SceneFileEntityVo.class);
		List<ScenePictureEntity> scenePictureEntity = scenePictureService.list(Wrappers.<ScenePictureEntity>lambdaQuery().eq(ScenePictureEntity::getSfId, sceneFile.getId()));
		List<PictureVo> pictureList = new ArrayList<>();
		if (scenePictureEntity!=null) {
			scenePictureEntity.forEach(item -> {
				PictureVo pictureVo = new PictureVo();
				pictureVo.setPicturePath(minioAPI.getCOMINFO() + "/" + MinioCommonBucket.HUATAI_PUB_BUCKET_URL + "/" + item.getPath());
				pictureVo.setContentType(item.getContentType());
				pictureVo.setIsMain(item.getIsMain());
				pictureList.add(pictureVo);
			});
			sceneFile.setPictureUrl(minioAPI.getCOMINFO() + "/" + MinioCommonBucket.HUATAI_PUB_BUCKET_URL + "/" + scenePictureEntity.get(0).getPath());
		}
		//设置返回场景文件路径
		sceneFileEntityVo.setPath("");
		if(StringUtil.isNotBlank(sceneFile.getPath())){
			String signedUrl = minioAPI.getSignedUrl(MinioBucket.MODEL_BUCKET_NAME_PRIVATE, sceneFile.getPath(), 86400);
			sceneFileEntityVo.setPath(signedUrl);
		}
		sceneFileEntityVo.setPictureList(pictureList);
		return sceneFileEntityVo;
	}

	/**
	 * 获取场景基本信息
	 *
	 * @param sfId
	 * @return
	 */
	@Override
	public SceneFileEntityVo getClintSceneFileInfo(Long usaId) {
		UserSceneAuthEntity entity = userSceneAuthService.getById(usaId);
		//解决客户端 出现随机传场景未授权现象
		if(entity == null || !entity.getUserId().equals(AuthUtil.getUser().getUserId())){
			throw new ServiceException("暂未授权");
		}
		SceneFileEntity sceneFile = super.getById(entity.getSfId());
		if (sceneFile == null) {
			throw new ServiceException("场景不存在");
		}
		List<ScenePictureEntity> scenePictureEntity = scenePictureService.list(Wrappers.<ScenePictureEntity>lambdaQuery().eq(ScenePictureEntity::getSfId, sceneFile.getId()));
		List<PictureVo> pictureList = new ArrayList<>();
		if (scenePictureEntity!=null) {
			scenePictureEntity.forEach(item -> {
				PictureVo pictureVo = new PictureVo();
				pictureVo.setPicturePath(minioAPI.getCOMINFO() + "/" + MinioCommonBucket.HUATAI_PUB_BUCKET_URL + "/" + item.getPath());
				pictureVo.setContentType(item.getContentType());
				pictureList.add(pictureVo);
			});
			sceneFile.setPictureUrl(minioAPI.getCOMINFO() + "/" + MinioCommonBucket.HUATAI_PUB_BUCKET_URL + "/" + scenePictureEntity.get(0).getPath());
		}
		//设置不返回场景文件路径
		sceneFile.setPath("");
		SceneFileEntityVo sceneFileEntityVo = BeanUtil.copyProperties(sceneFile, SceneFileEntityVo.class);
		sceneFileEntityVo.setPictureList(pictureList);
		return sceneFileEntityVo;
	}

}
